Skip to content

completion: zsh: support completion after "git -C <path>"#2155

Open
mobilutz wants to merge 1 commit into
gitgitgadget:masterfrom
mobilutz:zsh-complete-global-C
Open

completion: zsh: support completion after "git -C <path>"#2155
mobilutz wants to merge 1 commit into
gitgitgadget:masterfrom
mobilutz:zsh-complete-global-C

Conversation

@mobilutz

@mobilutz mobilutz commented Jun 17, 2026

Copy link
Copy Markdown

This patch is intentionally scoped to -C, but the underlying problem is more general. The zsh wrapper hard-codes __git_cmd_idx=1, i.e. it assumes the command is always the first argument. That assumption breaks argument completion after any global option that precedes the command, not just -C — e.g. --git-dir, --work-tree, --namespace, -c, and -p/--paginate. After those, git <opt> <command> <TAB> currently completes the command name but not its arguments.

The same approach generalizes cleanly: instead of skipping only leading -C options, walk all leading global options and their arguments to locate the command and its true index (mirroring the option scan in __git_main in git-completion.bash), while collecting -C into __git_C_args and --git-dir into __git_dir as today.

I kept this revision narrow for reviewability and because git -C is the case where I miss the completion, but I'm happy to extend it to cover the other global options in a follow-up (or fold it into this patch) if that's preferred.

cc: Ben Knoble ben.knoble@gmail.com

The zsh completion wrapper (__git_zsh_main) did not handle the global -C
option, so "git -C <path> <command> <TAB>" offered nothing and could not
complete a command's arguments.

Three things are needed to make it work, all scoped to -C:

  - Add -C to the _arguments specification, so completion no longer stops
    at it.

  - Advance __git_cmd_idx past any leading "-C <path>" options. The index
    is hard-coded to 1, i.e. the command is assumed to be the first
    argument; with -C present the command sits two words later for each
    -C, so the bash helpers otherwise look at the wrong word and produce
    nothing.

  - Collect the -C paths into __git_C_args, as __git_main does. The bash
    helpers run git to resolve aliases and list refs; without the -C
    paths they run in the current directory, so completion fails whenever
    the cwd is not the target repository or the command is an alias.

With these, "git -C <path> <command> <TAB>" completes the command, its
options and its arguments, including outside the repository, through
aliases, and with repeated -C options.

Signed-off-by: Lutz Lengemann <lutz@lengemann.net>
@gitgitgadget

gitgitgadget Bot commented Jun 17, 2026

Copy link
Copy Markdown

Welcome to GitGitGadget

Hi @mobilutz, and welcome to GitGitGadget, the GitHub App to send patch series to the Git mailing list from GitHub Pull Requests.

Please make sure that either:

  • Your Pull Request has a good description, if it consists of multiple commits, as it will be used as cover letter.
  • Your Pull Request description is empty, if it consists of a single commit, as the commit message should be descriptive enough by itself.

You can CC potential reviewers by adding a footer to the PR description with the following syntax:

CC: Revi Ewer <revi.ewer@example.com>, Ill Takalook <ill.takalook@example.net>

NOTE: DO NOT copy/paste your CC list from a previous GGG PR's description,
because it will result in a malformed CC list on the mailing list. See
example.

Also, it is a good idea to review the commit messages one last time, as the Git project expects them in a quite specific form:

  • the lines should not exceed 76 columns,
  • the first line should be like a header and typically start with a prefix like "tests:" or "revisions:" to state which subsystem the change is about, and
  • the commit messages' body should be describing the "why?" of the change.
  • Finally, the commit messages should end in a Signed-off-by: line matching the commits' author.

It is in general a good idea to await the automated test ("Checks") in this Pull Request before contributing the patches, e.g. to avoid trivial issues such as unportable code.

Contributing the patches

Before you can contribute the patches, your GitHub username needs to be added to the list of permitted users. Any already-permitted user can do that, by adding a comment to your PR of the form /allow. A good way to find other contributors is to locate recent pull requests where someone has been /allowed:

Both the person who commented /allow and the PR author are able to /allow you.

An alternative is the channel #git-devel on the Libera Chat IRC network:

<newcontributor> I've just created my first PR, could someone please /allow me? https://github.com/gitgitgadget/git/pull/12345
<veteran> newcontributor: it is done
<newcontributor> thanks!

Once on the list of permitted usernames, you can contribute the patches to the Git mailing list by adding a PR comment /submit.

If you want to see what email(s) would be sent for a /submit request, add a PR comment /preview to have the email(s) sent to you. You must have a public GitHub email address for this. Note that any reviewers CC'd via the list in the PR description will not actually be sent emails.

After you submit, GitGitGadget will respond with another comment that contains the link to the cover letter mail in the Git mailing list archive. Please make sure to monitor the discussion in that thread and to address comments and suggestions (while the comments and suggestions will be mirrored into the PR by GitGitGadget, you will still want to reply via mail).

If you do not want to subscribe to the Git mailing list just to be able to respond to a mail, you can download the mbox from the Git mailing list archive (click the (raw) link), then import it into your mail program. If you use GMail, you can do this via:

curl -g --user "<EMailAddress>:<Password>" \
    --url "imaps://imap.gmail.com/INBOX" -T /path/to/raw.txt

To iterate on your change, i.e. send a revised patch or patch series, you will first want to (force-)push to the same branch. You probably also want to modify your Pull Request description (or title). It is a good idea to summarize the revision by adding something like this to the cover letter (read: by editing the first comment on the PR, i.e. the PR description):

Changes since v1:
- Fixed a typo in the commit message (found by ...)
- Added a code comment to ... as suggested by ...
...

To send a new iteration, just add another PR comment with the contents: /submit.

Need help?

New contributors who want advice are encouraged to join git-mentoring@googlegroups.com, where volunteers who regularly contribute to Git are willing to answer newbie questions, give advice, or otherwise provide mentoring to interested contributors. You must join in order to post or view messages, but anyone can join.

You may also be able to find help in real time in the developer IRC channel, #git-devel on Libera Chat. Remember that IRC does not support offline messaging, so if you send someone a private message and log out, they cannot respond to you. The scrollback of #git-devel is archived, though.

@Ikke

Ikke commented Jun 17, 2026

Copy link
Copy Markdown

/allow

@gitgitgadget

gitgitgadget Bot commented Jun 17, 2026

Copy link
Copy Markdown

User mobilutz is now allowed to use GitGitGadget.

WARNING: mobilutz has no public email address set on GitHub; GitGitGadget needs an email address to Cc: you on your contribution, so that you receive any feedback on the Git mailing list. Go to https://github.com/settings/profile to make your preferred email public to let GitGitGadget know which email address to use.

@mobilutz

Copy link
Copy Markdown
Author

/preview

@gitgitgadget

gitgitgadget Bot commented Jun 17, 2026

Copy link
Copy Markdown

Preview email sent as pull.2155.git.1781710098703.gitgitgadget@gmail.com

@mobilutz

Copy link
Copy Markdown
Author

/submit

@gitgitgadget

gitgitgadget Bot commented Jun 17, 2026

Copy link
Copy Markdown

Submitted as pull.2155.git.1781710256081.gitgitgadget@gmail.com

To fetch this version into FETCH_HEAD:

git fetch https://github.com/gitgitgadget/git/ pr-2155/mobilutz/zsh-complete-global-C-v1

To fetch this version to local tag pr-2155/mobilutz/zsh-complete-global-C-v1:

git fetch --no-tags https://github.com/gitgitgadget/git/ tag pr-2155/mobilutz/zsh-complete-global-C-v1

@gitgitgadget

gitgitgadget Bot commented Jul 6, 2026

Copy link
Copy Markdown

Ben Knoble wrote on the Git mailing list (how to reply to this email):

I’d like to take a deeper look at this, but I’m not sure when I can.

> Le 17 juin 2026 à 11:37, Lutz Lengemann via GitGitGadget <gitgitgadget@gmail.com> a écrit :
> 
> From: Lutz Lengemann <lutz@lengemann.net>
> 
> The zsh completion wrapper (__git_zsh_main) did not handle the global -C
> option, so "git -C <path> <command> <TAB>" offered nothing and could not
> complete a command's arguments.

One easy note, though: our commit style prefers describing the code base before the patch in question in the present tense (« does not handle », « offers nothing »).

The below imperative mood looks appropriate to me.

> 
> Three things are needed to make it work, all scoped to -C:
> 
>  - Add -C to the _arguments specification, so completion no longer stops
>    at it.
> 
>  - Advance __git_cmd_idx past any leading "-C <path>" options. The index
>    is hard-coded to 1, i.e. the command is assumed to be the first
>    argument; with -C present the command sits two words later for each
>    -C, so the bash helpers otherwise look at the wrong word and produce
>    nothing.
> 
>  - Collect the -C paths into __git_C_args, as __git_main does. The bash
>    helpers run git to resolve aliases and list refs; without the -C
>    paths they run in the current directory, so completion fails whenever
>    the cwd is not the target repository or the command is an alias.
> 
> With these, "git -C <path> <command> <TAB>" completes the command, its
> options and its arguments, including outside the repository, through
> aliases, and with repeated -C options.
> 
> Signed-off-by: Lutz Lengemann <lutz@lengemann.net>
> ---
>    completion: zsh: support completion after "git -C "
> 
>    This patch is intentionally scoped to -C, but the underlying problem is
>    more general. The zsh wrapper hard-codes __git_cmd_idx=1, i.e. it
>    assumes the command is always the first argument. That assumption breaks
>    argument completion after any global option that precedes the command,
>    not just -C — e.g. --git-dir, --work-tree, --namespace, -c, and
>    -p/--paginate. After those, git <opt> <command> <TAB> currently
>    completes the command name but not its arguments.
> 
>    The same approach generalizes cleanly: instead of skipping only leading
>    -C options, walk all leading global options and their arguments to
>    locate the command and its true index (mirroring the option scan in
>    __git_main in git-completion.bash), while collecting -C into
>    __git_C_args and --git-dir into __git_dir as today.
> 
>    I kept this revision narrow for reviewability and because git -C is the
>    case where I miss the completion, but I'm happy to extend it to cover
>    the other global options in a follow-up (or fold it into this patch) if
>    that's preferred.
> 
> Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-2155%2Fmobilutz%2Fzsh-complete-global-C-v1
> Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2155/mobilutz/zsh-complete-global-C-v1
> Pull-Request: https://github.com/gitgitgadget/git/pull/2155
> 
> contrib/completion/git-completion.zsh | 9 +++++++++
> 1 file changed, 9 insertions(+)
> 
> diff --git a/contrib/completion/git-completion.zsh b/contrib/completion/git-completion.zsh
> index c32186a977..323049be8b 100644
> --- a/contrib/completion/git-completion.zsh
> +++ b/contrib/completion/git-completion.zsh
> @@ -227,6 +227,7 @@ __git_zsh_main ()
>        '(-p --paginate --no-pager)'{-p,--paginate}'[pipe all output into ''less'']' \
>        '(-p --paginate)--no-pager[do not pipe git output into a pager]' \
>        '--git-dir=-[set the path to the repository]: :_directories' \
> +        '*-C[run as if git was started in <path>]: :_directories' \
>        '--bare[treat the repository as a bare repository]' \
>        '(- :)--version[prints the git suite version]' \
>        '--exec-path=-[path to where your core git programs are installed]:: :_directories' \
> @@ -252,6 +253,14 @@ __git_zsh_main ()
>        ;;
>    (arg)
>        local command="${words[1]}" __git_dir __git_cmd_idx=1
> +        local -a __git_C_args
> +        local -i i=2
> +
> +        while [[ ${orig_words[i]} == -C ]]; do
> +            __git_C_args+=(-C ${orig_words[i+1]})
> +            (( __git_cmd_idx += 2 ))
> +            (( i += 2 ))
> +        done
> 
>        if (( $+opt_args[--bare] )); then
>            __git_dir='.'
> 
> base-commit: 0fae78c9d55efe705877ea537fe42c59164ccd94
> --
> gitgitgadget
> 

@gitgitgadget

gitgitgadget Bot commented Jul 6, 2026

Copy link
Copy Markdown

User Ben Knoble <ben.knoble@gmail.com> has been added to the cc: list.

@gitgitgadget

gitgitgadget Bot commented Jul 6, 2026

Copy link
Copy Markdown

Junio C Hamano wrote on the Git mailing list (how to reply to this email):

"Lutz Lengemann via GitGitGadget" <gitgitgadget@gmail.com> writes:

> From: Lutz Lengemann <lutz@lengemann.net>
>
> The zsh completion wrapper (__git_zsh_main) did not handle the global -C
> option, so "git -C <path> <command> <TAB>" offered nothing and could not
> complete a command's arguments.

I do not write, use, or customize zsh, so please take my comments
with huge grains of salt, or just ignore them completely (your
choice) ;-), but one thng I noticed was that ...

> diff --git a/contrib/completion/git-completion.zsh b/contrib/completion/git-completion.zsh
> index c32186a977..323049be8b 100644
> --- a/contrib/completion/git-completion.zsh
> +++ b/contrib/completion/git-completion.zsh
> @@ -227,6 +227,7 @@ __git_zsh_main ()
>  		'(-p --paginate --no-pager)'{-p,--paginate}'[pipe all output into ''less'']' \
>  		'(-p --paginate)--no-pager[do not pipe git output into a pager]' \
>  		'--git-dir=-[set the path to the repository]: :_directories' \
> +		'*-C[run as if git was started in <path>]: :_directories' \
>  		'--bare[treat the repository as a bare repository]' \
>  		'(- :)--version[prints the git suite version]' \
>  		'--exec-path=-[path to where your core git programs are installed]:: :_directories' \

... this part talks about not just "-C<dir>" but knows about
all the other options that the "git" potty itself takes, while ...

> @@ -252,6 +253,14 @@ __git_zsh_main ()
>  		;;
>  	(arg)
>  		local command="${words[1]}" __git_dir __git_cmd_idx=1
> +		local -a __git_C_args
> +		local -i i=2
> +
> +		while [[ ${orig_words[i]} == -C ]]; do
> +			__git_C_args+=(-C ${orig_words[i+1]})
> +			(( __git_cmd_idx += 2 ))
> +			(( i += 2 ))
> +		done

... this only knows about "-C<dir>" and nothing else.

Doesn't it want to do something similar to what __git_main in
git-completion.bash does at the beginning, namely, this part?

__git_main ()
{
	local i c=1 command __git_dir __git_repo_path
	local __git_C_args C_args_count=0
	local __git_cmd_idx

	while [ $c -lt $cword ]; do
		i="${words[c]}"
		case "$i" in
		--git-dir=*)
			__git_dir="${i#--git-dir=}"
			;;
		--git-dir)
			((c++))
			__git_dir="${words[c]}"
			;;
		--bare)
			__git_dir="."
			;;
		--help)
			command="help"
			break
			;;
		-c|--work-tree|--namespace)
			((c++))
			;;
		-C)
			__git_C_args[C_args_count++]=-C
			((c++))
			__git_C_args[C_args_count++]="${words[c]}"
			;;
		-*)
			;;
		*)
			command="$i"
			__git_cmd_idx="$c"
			break
			;;
		esac
		((c++))
	done

@gitgitgadget

gitgitgadget Bot commented Jul 6, 2026

Copy link
Copy Markdown

"D. Ben Knoble" wrote on the Git mailing list (how to reply to this email):

[apologies in advance for the strange format below]

On Wed, Jun 17, 2026 at 11:37 AM Lutz Lengemann via GitGitGadget
<gitgitgadget@gmail.com> wrote:
>
> From: Lutz Lengemann <lutz@lengemann.net>
>
> The zsh completion wrapper (__git_zsh_main) did not handle the global -C
> option, so "git -C <path> <command> <TAB>" offered nothing and could not
> complete a command's arguments.
>
> Three things are needed to make it work, all scoped to -C:
>
>   - Add -C to the _arguments specification, so completion no longer stops
>     at it.
>
>   - Advance __git_cmd_idx past any leading "-C <path>" options. The index
>     is hard-coded to 1, i.e. the command is assumed to be the first
>     argument; with -C present the command sits two words later for each
>     -C, so the bash helpers otherwise look at the wrong word and produce
>     nothing.
>
>   - Collect the -C paths into __git_C_args, as __git_main does. The bash
>     helpers run git to resolve aliases and list refs; without the -C
>     paths they run in the current directory, so completion fails whenever
>     the cwd is not the target repository or the command is an alias.
>
> With these, "git -C <path> <command> <TAB>" completes the command, its
> options and its arguments, including outside the repository, through
> aliases, and with repeated -C options.
>
> Signed-off-by: Lutz Lengemann <lutz@lengemann.net>
> ---
>     completion: zsh: support completion after "git -C "
>
>     This patch is intentionally scoped to -C, but the underlying problem is
>     more general. The zsh wrapper hard-codes __git_cmd_idx=1, i.e. it
>     assumes the command is always the first argument. That assumption breaks
>     argument completion after any global option that precedes the command,
>     not just -C — e.g. --git-dir, --work-tree, --namespace, -c, and
>     -p/--paginate. After those, git <opt> <command> <TAB> currently
>     completes the command name but not its arguments.
>
>     The same approach generalizes cleanly: instead of skipping only leading
>     -C options, walk all leading global options and their arguments to
>     locate the command and its true index (mirroring the option scan in
>     __git_main in git-completion.bash), while collecting -C into
>     __git_C_args and --git-dir into __git_dir as today.
>
>     I kept this revision narrow for reviewability and because git -C is the
>     case where I miss the completion, but I'm happy to extend it to cover
>     the other global options in a follow-up (or fold it into this patch) if
>     that's preferred.

See Junio's review for whether we should expand in this patch or a follow-up.

In reply to Junio:

> [the new handling only knows about -C]
> Doesn't it want to do something similar to what __git_main in
> git-completion.bash does at the beginning, namely, this part?

Yeah, we probably do want to skip over -c, etc. (I see some support for
--bare and --git-dir, but not skipping over it.) Still, this patch makes
things no worse in that regard, and improves the situation for -C
AFAICT.

In reply to Lutz:

> +        local -a __git_C_args
> +        local -i i=2
> +
> +        while [[ ${orig_words[i]} == -C ]]; do
> +            __git_C_args+=(-C ${orig_words[i+1]})
> +            (( __git_cmd_idx += 2 ))
> +            (( i += 2 ))
> +        done

I don't see either of these 2 local variables used anywhere else…

…well, except the Bash completion helpers, I suppose. But we mark these
local, so how do they propagate to the other functions?

Still, I was able to try this out with the somewhat hacky

    zsh # new shell :)
    # absolute path important
    autoload -Uz $PWD/contrib/completion/git-completion.zsh
    compdef git-completion.zsh git

    git -C <tab>

and it does prioritize directories there (though I still get a listing
of files afterwards, so the screen is taken up by that gigantic listing
in git.git, for example).

By the way, I've realized that "git -<tab>" has the same problem (a
giant list of files after the other option completions), and worse has
some _funky_ output!

    git -<tab> # without patch
    (option)
    --bare
    --exec-path
    --git-dir
    --help
    --html-path
    --info-path
    --man-path
    --namespace
    --no-pager
    --no-replace-objects
    --paginate
    --version
    --work-tree

    -p

    # treat the repository as a bare repository
    # path to where your core git programs are installed
    # set the path to the repository
    # prints the synopsis and a list of the most commonly used commands
    # print the path where gits HTML documentation is installed
    # print the path where the Info files are installed
    # print the manpath (see `man(1)`) for the man pages
    # set the git namespace
    # do not pipe git output into a pager
    # do not use replacement refs to replace git objects
    # pipe all output into less
    # prints the git suite version
    # set the path to the working tree
    [ed: the above block repeats twice more before the (file) listing below]
    (file)
    […]

Here's the output of _complete_help (^Xh by default) in both situations,
in case that helps to understand either the extra files listing (1) in
the example further back or the issue with single letter options (2)
just mentioned:

1: tags in context :completion::complete:git::
    option-C-1     (_arguments __git_zsh_main _git git-completion.zsh)
    use-compctl    (_default _git git-completion.zsh)
    globbed-files  (_files _default _git git-completion.zsh)
tags in context :completion::complete:git:option-C-1:
    directories    (_directories _arguments __git_zsh_main _git
git-completion.zsh)
    globbed-files  (_files _directories _arguments __git_zsh_main _git
git-completion.zsh)
    all-files      (_files _directories _arguments __git_zsh_main _git
git-completion.zsh)

2: tags in context :completion::complete:git::
    argument-1 options  (_arguments __git_zsh_main _git)
    use-compctl         (_default _git)
    globbed-files       (_files _default _git)
tags in context :completion::complete:git:argument-1:
    common-commands alias-commands all-commands  (__git_zsh_main _git)
    common-commands                              (__git_zsh_cmd_common
__git_zsh_main _git)
    alias-commands                               (__git_zsh_cmd_alias
__git_zsh_main _git)
    all-commands                                 (__git_zsh_cmd_all
__git_zsh_main _git)
tags in context :completion::complete:git:options:
    options  (_arguments __git_zsh_main _git)

> +        '*-C[run as if git was started in <path>]: :_directories' \

We should probably note in the log message that the _directories
completion will not account for previous -C; that is, after typing

    git -C dir -C <tab>

we will complete directories in ".", not "dir". That's probably a
reasonable limitation for now, but I think we could do _slightly_ better
by using a state "->dir" or something, accumulating the current prefix,
and passing that to _directories as a prefix with -W (see _path_files in
zshcompsys, which _directories delegates to via _files, IIUC).

-- 
D. Ben Knoble

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants